<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList">
          查询
        </el-button>
        <el-button @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      v-permission="'btn.User.add'"
      @click="showAddDialogForm"
    >
      添加
    </el-button>
    <el-button type="danger" v-permission="'btn.User.remove'" :disabled="true">
      批量删除
    </el-button>

    <el-table border :data="userList" class="mt-20" v-loading="loading">
      <el-table-column width="60" align="center" type="selection" />
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column label="用户名" width="190" prop="username" />
      <el-table-column label="用户昵称" width="190" prop="nickName" />
      <el-table-column label="角色列表" width="190" prop="roleName" />
      <el-table-column label="创建时间" width="190" prop="gmtCreate" />
      <el-table-column label="更新时间" width="190" prop="gmtModified" />
      <el-table-column label="操作" width="190" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button
            :icon="User"
            type="info"
            size="small"
            v-permission="'btn.User.assgin'"
            @click="showSetRolesDialog(row)"
          />
          <el-button
            :icon="Edit"
            type="warning"
            size="small"
            @click="showUpdateDialogForm(row)"
            v-permission="'btn.User.update'"
          />
          <el-popconfirm
            @confirm="deleteUser(row.id)"
            :title="`你确定要删除用户${row.username}吗？`"
          >
            <template #reference>
              <el-button
                :icon="Delete"
                type="danger"
                size="small"
                v-permission="'btn.User.remove'"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-20"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
    />

    <el-dialog
      v-model="addOrUpdateDialogFormVisible"
      :title="`${addOrUpdateDialogFormData.id ? '修改' : '添加'}用户`"
    >
      <el-form
        label-width="100"
        ref="addOrUpdateDialogFormRef"
        :model="addOrUpdateDialogFormData"
        :rules="addOrUpdateDialogFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="addOrUpdateDialogFormData.username"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            placeholder="请输入用户昵称"
            v-model="addOrUpdateDialogFormData.nickName"
          />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            type="password"
            placeholder="请输入用户密码"
            v-model="addOrUpdateDialogFormData.password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addOrUpdateDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="setRolesDialogFormVisible" title="设置角色">
      <el-form
        ref="setRolesDialogFormRef"
        :model="setRolesDialogFormData"
        :rules="setRolesDialogFormRules"
      >
        <el-form-item label="用户名">
          <el-input :value="setRolesDialogFormData.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="setRolesDialogFormData.roleId"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="Roles in allRolesList"
              :key="Roles.id"
              :label="Roles.id"
            >
              {{ Roles.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="userDoAssign">保存</el-button>
        <el-button @click="setRolesDialogFormVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Delete, Edit, Search, User } from "@element-plus/icons-vue";
import {
  getUserListApi,
  addUserApi,
  updateUserApi,
  removeUserApi,
  getRoleListsApi,
  userDoAssignApi,
} from "@/api/acl/user";
import type {
  GetUserList,
  GetUserItem,
  RolesList,
} from "@/api/acl/model/userModel";
import { ElMessage } from "element-plus";
import type { CheckboxValueType } from "element-plus";
/********************************设置角色相关*************************************/
// 是否显示对话框
const setRolesDialogFormVisible = ref(false);
// 全部角色列表
const allRolesList = ref<RolesList>([]);
// 是否全选
const checkAll = ref(false);
// 是否处于中间状态
const isIndeterminate = ref(false);

// 🐷点击保存按钮
const userDoAssign = async () => {
  // 表单校验
  await setRolesDialogFormRef.value.validate();
  await userDoAssignApi(
    setRolesDialogFormData.userId,
    setRolesDialogFormData.roleId
  );
  getUserList();
  setRolesDialogFormVisible.value = false;
  ElMessage.success("角色分配成功");
};

// 校验表单
const setRolesDialogFormRef = ref();
const setRolesDialogFormData = reactive<{
  userId: string;
  roleId: string[];
  username: string;
}>({
  userId: "",
  roleId: [],
  username: "",
});
const setRolesDialogFormRules = reactive({
  roleId: [{ required: true, message: "请至少选择一个角色" }],
});
// 点击全选全不选触发的函数
const handleCheckAllChange = () => {
  // 全选
  if (checkAll.value) {
    setRolesDialogFormData.roleId = allRolesList.value.map((item) => item.id);
    isIndeterminate.value = false;
  }
  // 全不选
  else {
    setRolesDialogFormData.roleId = [];
    isIndeterminate.value = false;
  }
};

// 点击下方复选框组触发的函数
const handleCheckedRolesChange = (value: CheckboxValueType[]) => {
  // 全部不选中
  if (!value.length) {
    checkAll.value = false;
    isIndeterminate.value = false;
  }
  // 全部选中
  else if (value.length === allRolesList.value.length) {
    checkAll.value = true;
    isIndeterminate.value = false;
  }
  // 既没有全部选中又没有全部不选中
  else {
    setRolesDialogFormData.roleId = value as string[];
    // checkAll.value = false;
    isIndeterminate.value = true;
  }
};
const showSetRolesDialog = async (row: GetUserItem) => {
  // 赋值
  setRolesDialogFormData.username = row.username;
  setRolesDialogFormData.userId = row.id;
  // 发送请求
  const res = await getRoleListsApi(row.id);
  allRolesList.value = res.allRolesList;
  setRolesDialogFormData.roleId = res.assignRoles.map((item) => item.id);
  // 显示对话框
  setRolesDialogFormVisible.value = true;
};

/**********************************删除用户***************************************/
const deleteUser = async (id: string) => {
  // 发送请求
  await removeUserApi(id);
  // 重新获取数据
  getUserList();
  // 提示用户
  ElMessage.success("删除成功");
};
/**********************************修改用户***************************************/
const showUpdateDialogForm = (row: GetUserItem) => {
  // 显示对话框
  addOrUpdateDialogFormVisible.value = true;
  // 赋值
  addOrUpdateDialogFormData.id = row.id;
  addOrUpdateDialogFormData.username = row.username;
  addOrUpdateDialogFormData.nickName = row.nickName;
  // 密码需要自己输入
  addOrUpdateDialogFormData.password = "";
  // 清空表单校验规则
  addOrUpdateDialogFormRef.value?.clearValidate();
};
// 点击确定按钮
// 与添加共用一个
/**********************************添加用户***************************************/
// 对话框显示隐藏的标识
const addOrUpdateDialogFormVisible = ref(false);
// 绑定表单
const addOrUpdateDialogFormRef = ref();
// 收集表单数据
const addOrUpdateDialogFormData = reactive({
  id: "",
  username: "",
  nickName: "",
  password: "",
});
// 表单校验规则
const addOrUpdateDialogFormRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

// 🐷确定按钮
const confirm = async () => {
  // 验证表单
  await addOrUpdateDialogFormRef.value.validate();
  // 发送请求
  const id = addOrUpdateDialogFormData.id;
  if (id) {
    // 修改请求
    await updateUserApi(addOrUpdateDialogFormData);
  } else {
    // 添加请求
    await addUserApi(addOrUpdateDialogFormData);
  }
  // 重新发送请求
  getUserList();
  // 关闭对话框
  addOrUpdateDialogFormVisible.value = false;
  // 提示用户
  ElMessage.success(`${id ? "修改" : "添加"}用户成功`);
};
// 🐷添加按钮
const showAddDialogForm = () => {
  // 显示对话框
  addOrUpdateDialogFormVisible.value = true;
  // 清空表单
  addOrUpdateDialogFormData.id = "";
  addOrUpdateDialogFormData.username = "";
  addOrUpdateDialogFormData.nickName = "";
  addOrUpdateDialogFormData.password = "";
  // 清除校验结果
  addOrUpdateDialogFormRef.value?.clearValidate();
};
/**********************************展示数据***************************************/
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const username = ref("");
const userList = ref<GetUserList>([]);
const getUserList = async () => {
  loading.value = true;
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  userList.value = res.items;
  total.value = res.total;
  loading.value = false;
};
// 挂载时请求数据
onMounted(getUserList);
// 点击清空按钮
const resetSearch = () => {
  username.value = "";
  getUserList();
};
</script>

<style scoped></style>
